import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'umi';
import { withRouter, router } from 'umi';
import { Card, Tag, Steps, Form, Row, Col, Button, message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import request from '@/utils/request';
import { withRoutePage } from '@/utils/enhanceUtils';
import { countryDict } from '@/models/mineList';
import { readStatusMap, useSetReadStatus } from '@/hooks/useSetReadStatus';

import clone from 'lodash/clone';
import { useDetail } from './utils';
import styles from './Wrap.less';

const { Step } = Steps;
const { Item } = Form;

const processPush = async data => {
    const response = await request('/api/oa/v1/system/process/push', {
        method: 'POST',
        data
    });
    return response;
};

const Wrap = ({ form, formElement, location, formItemLayout, tailFormItemLayout, user }) => {
    const { query } = location;
    const { processTemplateId, processInstanceId, transferPostId, isOtherPost, type } = query;
    const { currentUser } = user;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [rejectLoading, setRejectLoading] = React.useState(false);
    const [cancelLoading, setCancelLoading] = React.useState(false);

    const editQuery = {
        transferPostId,
        user: currentUser,
        isOther: isOtherPost,
        processInstanceId: '',
        processTemplateId: '',
        type
    };

    const addQuery = {
        transferPostId: '',
        processInstanceId,
        processTemplateId,
        user: currentUser,
        isOther: isOtherPost,
        type
    };

    const { detail, loading } = useDetail(transferPostId ? editQuery : addQuery);
    const { processTaskInstances, processTaskTemplates, currentProcessTaskInstance, startAssigneeEmployeeId } = detail;
    const { relatedBusinessObject = {}, taskPath = '', assigneeEmployeeIds = '' } = currentProcessTaskInstance;
    const { companyId, employeeName, currentProcessTasDesc = '', lastConfirmDate } = relatedBusinessObject;

    useSetReadStatus({ id: processInstanceId, type: readStatusMap.TRANSFER });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                setSubmitLoading(true);
                // 如果当前调岗不是被退回;只有第一步才需要检测
                if (detail.processState !== 'failed' && !transferPostId) {
                    const checkResponse = await request(
                        '/api/oa/v1/transferposts/actions/onlycheck?' +
                            `employeeId=${isOtherPost ? form.getFieldValue('employeeId') : currentUser.id}` +
                            `&userNo=${isOtherPost ? form.getFieldValue('userNo') : currentUser.userNo}`
                    );
                    if (checkResponse.code !== 10000) {
                        message.error(checkResponse.msg);
                        setSubmitLoading(false);
                        return;
                    }
                }
                if (
                    values.prePostId === values.afterPostId &&
                    values.preDepartmentId ===
                        (values.afterDepartmentId && Array.isArray(values.afterDepartmentId)
                            ? clone(values.afterDepartmentId).pop()
                            : values.afterDepartmentId)
                ) {
                    message.error('不允许调岗到同一职位！');
                    setSubmitLoading(false);
                    return;
                }
                const { afterDepartmentId } = values;
                const data = {
                    id: transferPostId || '',
                    currentAction: 'forwardToNextTask',
                    processTemplateId: transferPostId ? detail.processTemplateId : processTemplateId,
                    processInstanceId: transferPostId ? detail.processInstanceId : processInstanceId,
                    relatedBusinessKey: `afterDepartmentId:${(afterDepartmentId && Array.isArray(afterDepartmentId)
                        ? clone(afterDepartmentId).pop()
                        : afterDepartmentId) || detail.afterDepartmentId},`,
                    relatedBusinessObject: {
                        ...values,
                        afterDepartmentId:
                            afterDepartmentId && Array.isArray(afterDepartmentId)
                                ? clone(afterDepartmentId).pop()
                                : afterDepartmentId,
                        transferDate: values.transferDate.format('YYYY-MM-DD'),
                        id: relatedBusinessObject.id || ''
                    }
                };
                if (processInstanceId) data.processInstanceId = processInstanceId;
                const response = await processPush(data);
                if (response.code === 10000) {
                    message.success('提交成功！');
                    history.push('/personal/portal/myOnboardAndLeave/myAdjustPost');
                } else {
                    message.error(response.msg);
                    setSubmitLoading(false);
                }
            }
        });
    };

    const isEdit = transferPostId;
    const current = transferPostId ? taskPath.length / 3 - 1 : 0;

    const getDescription = () => {
        const find = curCompanyId => countryDict.find(country => country.id === curCompanyId);
        return [
            isOtherPost ? '他人调岗申请' : `调岗${isEdit ? '详情' : '申请'}`,
            companyId ? find(companyId).name : find(currentUser.companyId).name,
            employeeName || currentUser.employeeName
        ].join('-');
    };

    const handleReject = async () => {
        setRejectLoading(true);
        const { employeeId, companyId: curCompanyId } = form.getFieldsValue();
        const data = {
            currentAction: 'backwardToPreviousTask',
            processTemplateId: detail.processTemplateId,
            processInstanceId: detail.processInstanceId,
            id: transferPostId || '',
            relatedBusinessObject: {
                employeeId,
                companyId: curCompanyId
            }
        };

        const response = await processPush(data);
        if (response.code === 10000) {
            message.success('退回成功！');
            history.push('/personal/portal/myOnboardAndLeave/myAdjustPost');
        } else {
            message.error(response.msg);
            setRejectLoading(false);
        }
    };

    const handleCancel = async () => {
        if (!transferPostId) {
            history.push('/personal/portal/flow/mine/list');
        } else {
            setCancelLoading(true);
            const response = await processPush({
                currentAction: 'resetToFirstTask',
                id: transferPostId || '',
                processTemplateId: detail.processTemplateId,
                processInstanceId: detail.processInstanceId
            });

            if (response.code === 10000) {
                message.success('撤销成功！');
                history.push('/personal/portal/flow/mine/list');
            } else {
                message.error(response.msg);
                setCancelLoading(false);
            }
        }
    };

    const getStatus = (taskTemplateId, index) => {
        if (detail.processState === 'success') return 'finish';
        if (!transferPostId) {
            if (index === 0) {
                return 'process';
            }
            return 'wait';
        }

        if (current === index) return 'process';
        if (index < current) return 'finish';
        const find = processTaskInstances.find(item => item.taskTemplateId === taskTemplateId);

        if (find && find.assigneeAction === 'backwardToPreviousTask') {
            return 'error';
        }
        return 'wait';
    };

    const renderCancelBtn = () => {
        // 新增时、被退回时、且是发起人
        if ((!transferPostId || detail.processState === 'failed') && startAssigneeEmployeeId === `${currentUser.id}`) {
            return (
                <Col>
                    <Button loading={cancelLoading} onClick={handleCancel}>
                        撤销
                    </Button>
                </Col>
            );
        }
        return null;
    };

    const renderBackBtn = () => {
        // 当前操作人且处于编辑，且不能是第一步
        if (transferPostId && assigneeEmployeeIds.split(',').includes(`${currentUser.id}`) && taskPath.length !== 3) {
            return (
                <Col>
                    <Button loading={rejectLoading} onClick={handleReject}>
                        退回
                    </Button>
                </Col>
            );
        }
        return null;
    };

    const btns = (
        <Item style={{ marginBottom: 4 }} {...tailFormItemLayout}>
            <Row justify="start" type="flex" gutter={12}>
                <Col>
                    <Button loading={submitLoading} type="primary" onClick={handleSubmit}>
                        提交
                    </Button>
                </Col>
                {renderCancelBtn()}
                {renderBackBtn()}
            </Row>
        </Item>
    );
    return (
        <PageHeaderWrapper type="success">
            <Card loading={loading} bordered={false}>
                {!(isOtherPost && !transferPostId) && (
                    <Row className={styles.titleBox} type="flex">
                        <Col>
                            <h3 className={styles.title}>{getDescription()}</h3>
                        </Col>
                        {lastConfirmDate && (
                            <>
                                <Col>
                                    <Tag color="orange" className={styles.status}>
                                        {currentProcessTasDesc}
                                    </Tag>
                                </Col>
                                <Col>
                                    <span className={styles.time}>最晚确认时间 {lastConfirmDate}</span>
                                </Col>
                            </>
                        )}
                    </Row>
                )}
                <Steps className={styles.steps}>
                    {processTaskTemplates.map(({ id, taskName, taskTemplateId }, index) => {
                        const status = getStatus(taskTemplateId, index);
                        return (
                            <Step
                                status={status}
                                title={taskName}
                                description={status === 'error' ? '(已退回)' : ''}
                                key={id}
                            />
                        );
                    })}
                </Steps>
                <h5 className={styles.subTitle}>员工基本信息</h5>
                <Form {...formItemLayout}>
                    {formElement({
                        user: currentUser,
                        form,
                        btns,
                        detail,
                        location,
                        formItemLayout,
                        tailFormItemLayout
                    })}
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

Wrap.propTypes = {
    formElement: PropTypes.func.isRequired,
    formItemLayout: PropTypes.object,
    tailFormItemLayout: PropTypes.object
};

Wrap.defaultProps = {
    formItemLayout: {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 4 }
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 10 }
        }
    },
    tailFormItemLayout: {
        wrapperCol: {
            xs: {
                span: 24,
                offset: 0
            },
            sm: {
                span: 10,
                offset: 4
            }
        }
    }
};

export default withRoutePage(connect(({ user }) => ({ user }))(Form.create()(withRouter(Wrap))));
